package com.cy.pet.forum.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.pet.common.mapper.CommentMapper;
import com.cy.pet.common.mapper.TopicMapper;
import com.cy.pet.common.pojo.Comment;
import com.cy.pet.common.pojo.Item;
import com.cy.pet.common.pojo.Topic;
import com.cy.pet.common.service.ForumService;
import com.cy.pet.common.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/10/8 10:48
 */
@Service
public class ForumServiceImpl implements ForumService {

    @Autowired
    private TopicMapper topicMapper;

    @Override
    public PageResult findAllTopicList(PageResult pageResult) throws ParseException {
        IPage page = new Page(pageResult.getPageNum(), pageResult.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag, "title", pageResult.getQuery())
                .orderByDesc("created");
        //执行分页查询,返回值依然是分页对象信息
        page = topicMapper.selectPage(page, queryWrapper);
        //回传5个参数 total/分页后的数据
        long total = page.getTotal();
        List<Item> rows = page.getRecords();
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    public List<Topic> findHotTopicList() {
        return topicMapper.findHotTopicList();
    }

    @Override
    public Topic findATopicById(Integer id) {
        QueryWrapper<Topic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return topicMapper.selectOne(queryWrapper);
    }
    @Transactional
    @Override
    public void addTopic(Topic topic) {
        topic.setCreated(new Date());

        topicMapper.insert(topic);
    }

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<Comment> findAllCommentByTopicId(Integer id) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("topic_id", id);
        return commentMapper.selectList(queryWrapper);
    }
    @Transactional
    @Override
    public void saveComment(Comment comment) {
        commentMapper.insert(comment);

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("topic_id", comment.getTopicId());
        Integer count = commentMapper.selectCount(queryWrapper);

        Topic topic = findATopicById(comment.getTopicId());
        topic.setCount(count);
        System.out.println("count = " + count);
        topicMapper.updateById(topic);
    }
}
